﻿Public Class Planilla_Egreso
    Enum estado
        insertar
        modificar
    End Enum
    Enum termino
        aprobado
        rechazado
    End Enum

    Dim accion As estado = estado.insertar
    Dim acceso As acceso_a_datos
    Dim idselected As Integer
    Dim combo_Doc_Com As New combo
    Dim codigo_Egreso As Integer
    Dim primera_busqueda As Boolean = False

    'CARGAR VENTANA 
    Private Sub Planilla_Egreso_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        acceso = New acceso_a_datos()
        Me.combo_Doc_Com.cadena_conexion = acceso._CadenaConexion
        Me.acceso._tabla = "Documento_Comercial"

        Me.combo_Doc_Com.cargar(Me.cmb_documento_com, Me.acceso.leo_tabla("cod_Doc_Comercial", "nombre"))
        Me.deshabilitar_Campos()
        Me.carga_grilla()
    End Sub

    'BOTON VOLVER
    Private Sub btn_volver_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_volver.Click
        Me.Close()
        Encargado.Show()
    End Sub

    'BOTON NUEVO
    Private Sub btn_nuevo_Click(sender As System.Object, e As System.EventArgs) Handles btn_nuevo.Click
        Me.habilitar_Campos()
        Me.mask_fecha.Focus()
        Me.limpiar_campos()
        Me.carga_grilla()
        accion = estado.insertar
        Me.primera_busqueda = False
    End Sub

    'BOTON GUARDAR
    Private Sub btn_guardar_Click(sender As System.Object, e As System.EventArgs) Handles btn_guardar.Click
        If Me.validar(sender, e) = True And accion = estado.insertar Then
            If insertar_Egreso() = termino.aprobado Then
                MessageBox.Show("Exito al Grabar en Base de Datos", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                limpiar_campos()
                deshabilitar_Campos()
                btn_guardar.Enabled = False
                carga_grilla()
                Me.primera_busqueda = False
            End If
        Else
            If Me.validar(sender, e) = True And accion = estado.modificar Then
                If modificar_Egreso() = termino.aprobado Then
                    MessageBox.Show("Exito al Grabar en Base de Datos", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                    limpiar_campos()
                    deshabilitar_Campos()
                    btn_guardar.Enabled = False
                    carga_grilla()
                    Me.primera_busqueda = False
                End If
            End If
        End If
    End Sub

    Private Sub deshabilitar_Campos()
        'campos
        Me.mask_fecha.Enabled = False
        Me.txt_prov.Enabled = False
        Me.txt_desc.Enabled = False
        Me.cmb_documento_com.Enabled = False
        Me.txt_docu_come.Enabled = False
        Me.txt_Monto.Enabled = False
        Me.cmb_documento_com.SelectedIndex = -1
        'botones
        Me.btn_buscar.Enabled = True
        Me.btn_eliminar.Enabled = False
        Me.btn_guardar.Enabled = False
    End Sub

    Private Sub habilitar_Campos()
        'campos
        Me.mask_fecha.Enabled = True
        Me.txt_prov.Enabled = True
        Me.txt_desc.Enabled = True
        Me.cmb_documento_com.Enabled = True
        Me.txt_docu_come.Enabled = True
        Me.txt_Monto.Enabled = True

        'botones
        Me.btn_buscar.Enabled = True
        Me.btn_eliminar.Enabled = False
        Me.btn_guardar.Enabled = True
    End Sub

    Private Sub limpiar_campos()
        Me.mask_fecha.Text = ""
        Me.txt_prov.Text = ""
        Me.txt_desc.Text = ""
        Me.cmb_documento_com.SelectedIndex = -1
        Me.txt_docu_come.Text = ""
        Me.txt_Monto.Text = ""
        lbl_descripcion_obligatorio.Visible = False
        lbl_documento_obligatorio.Visible = False
        lbl_monto_obligatorio.Visible = False
        lbl_proveedor_obligatorio.Visible = False
    End Sub

    'CARGAR GRILLA
    Private Sub carga_grilla()
        Dim tabla As New Data.DataTable
        Dim txt_sql As String = ""
        Dim c As Integer = 0

        txt_sql = "SELECT E.cod_Egreso as cod, E.fecha, DE.descripcion as des, DE.nombre_Proveedor as nom_Prov, DE.monto, DE.num_Doc_Com as num, DC.nombre "
        txt_sql += "FROM Egreso E INNER JOIN Detalle_Egreso DE ON E.cod_Egreso=DE.cod_Egreso "
        txt_sql += "INNER JOIN Documento_Comercial DC ON DC.cod_Doc_Comercial=DE.cod_Documento_Comercial"

        'obtengo los datos de la consulta
        tabla = Me.acceso._consulta(txt_sql)

        Me.grilla_Egreso.Rows.Clear()

        For c = 0 To tabla.Rows.Count - 1
            Me.grilla_Egreso.Rows.Add(tabla.Rows(c)("cod"), FormatDateTime(tabla.Rows(c)("fecha"), DateFormat.ShortDate), tabla.Rows(c)("des"), tabla.Rows(c)("nom_Prov"), tabla.Rows(c)("nombre"), tabla.Rows(c)("num"), tabla.Rows(c)("monto"))
        Next
    End Sub

    'VALIDAR DATOS
    Private Function validar(ByVal sender As System.Object, ByVal e As System.EventArgs) As Boolean
        If Me.mask_fecha.Text = "" Then
            'MessageBox.Show("Debe completar el campo Fecha", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.mask_fecha.Focus()
            Return False
            Exit Function
        End If

        If Me.txt_desc.Text = "" Then
            'MessageBox.Show("Debe completar el campo Descripción", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.mask_fecha.Focus()
            Return False
            Exit Function
        End If

        If Me.txt_prov.Text = "" Then
            'MessageBox.Show("Debe completar el campo Proveedor", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.txt_prov.Focus()
            Return False
            Exit Function
        End If

        If Me.cmb_documento_com.SelectedIndex = -1 Then
            MessageBox.Show("Debe seleccionar un Documento Comercial", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)

            Me.cmb_documento_com.Focus()
            Return False
            Exit Function
        End If

        If Me.txt_docu_come.Text = "" Then
            'MessageBox.Show("Debe completar el Numero de Doc Comercial", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.txt_docu_come.Focus()
            Return False
            Exit Function
        End If

        If Me.txt_Monto.Text = "" Then
            'MessageBox.Show("Debe completar el Monto", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.txt_Monto.Focus()
            Return False
            Exit Function
        End If

        Return True
    End Function

    'INSERTAR EN TABLA
    Private Function insertar_Egreso() As termino
        'grabamos datos tabla Egreso
        acceso._tabla = "Egreso"
        Dim consulta As String = ""
        Dim aux = obtenerId(acceso._tabla) + 1

        consulta = "cod_Egreso=" & aux
        consulta += ", fecha=" & Me.mask_fecha.Text
        consulta += ", monto_Total=" & Me.txt_Monto.Text

        Try
            acceso._insertar(consulta)
        Catch ex As Exception
            MessageBox.Show("Error al Insertar EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return termino.rechazado
            Exit Function
        End Try

        'grabamos datos tabla Detalle_Egreso
        acceso._tabla = "Detalle_Egreso"
        consulta = ", cod_Egreso=" & aux
        consulta += ", cod_Detalle_Egreso=" & obtenerId(acceso._tabla) + 1
        consulta += ", cod_Documento_Comercial=" & Me.cmb_documento_com.SelectedIndex
        consulta += ", nombre_Proveedor=" & Me.txt_prov.Text
        consulta += ", monto=" & Me.txt_Monto.Text
        consulta += ", descripcion=" & Me.txt_desc.Text
        consulta += ", num_Doc_Com=" & Me.txt_docu_come.Text

        Try
            acceso._insertar(consulta)
            Return termino.aprobado
        Catch ex2 As Exception
            MessageBox.Show("Error al Insertar DETALLE EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex2.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            acceso._borrar("DELETE FROM Egreso WHERE cod_Egreso=" & aux)
            Return termino.rechazado
            Exit Function
        End Try
    End Function

    'MODIFICAR TABLA
    Private Function modificar_Egreso() As termino
        'actualizamos datos tabla Egreso
        acceso._tabla = "Egreso"
        Dim valores As String = ""
        Dim restriccion As String = ""

        valores = "fecha=" & Me.mask_fecha.Text
        restriccion = "cod_Egreso=" & codigo_Egreso

        Try
            acceso._modificar(valores, restriccion)
        Catch ex As Exception
            MessageBox.Show("Error al Modificar EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return termino.rechazado
            Exit Function
        End Try

        'actualizamos datos tabla Detalle_Egreso
        acceso._tabla = "Detalle_Egreso"
        valores = "cod_Documento_Comercial=" & Me.cmb_documento_com.SelectedIndex
        valores += ", nombre_Proveedor=" & Me.txt_prov.Text
        valores += ", descripcion=" & Me.txt_desc.Text
        valores += ", num_Doc_Com=" & Me.txt_docu_come.Text

        restriccion = "cod_Egreso=" & codigo_Egreso

        Try
            acceso._modificar(valores, restriccion)
            Return termino.aprobado
        Catch ex2 As Exception
            MessageBox.Show("Error al Modificar DETALLE EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex2.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return termino.rechazado
            Exit Function
        End Try
    End Function

    'OBTENER ID
    Public Function obtenerId(ByRef tabla_ref As String) As Integer
        acceso._tabla = tabla_ref

        Dim tabla As Data.DataTable

        Try
            tabla = acceso._consulta("select max(cod_Egreso) as id from Egreso")

            If tabla.Rows.Count = 1 Then
                Return tabla.Rows(0)("id")
            Else
                Return 0
            End If
        Catch ex As InvalidCastException
            Return 0
        End Try
    End Function

    'DOBLE CLICK GRILLA
    Private Sub grilla_Egreso_CellContentDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla_Egreso.CellContentDoubleClick
        codigo_Egreso = Me.grilla_Egreso.CurrentRow.Cells("Codigo").Value
        Dim tabla As New Data.DataTable

        tabla = acceso._consulta("SELECT * FROM Egreso E INNER JOIN Detalle_Egreso DE ON E.cod_Egreso=DE.cod_Egreso WHERE E.cod_Egreso=" & codigo_Egreso)

        Me.habilitar_Campos()
        Me.btn_eliminar.Enabled = True
        Me.txt_Monto.Enabled = False

        Me.mask_fecha.Text = tabla.Rows(0)("fecha")
        Me.txt_desc.Text = tabla.Rows(0)("descripcion")
        Me.txt_prov.Text = tabla.Rows(0)("nombre_Proveedor")
        Me.cmb_documento_com.SelectedValue = tabla.Rows(0)("cod_Documento_Comercial")
        Me.txt_docu_come.Text = tabla.Rows(0)("num_Doc_Com")
        Me.txt_Monto.Text = tabla.Rows(0)("monto")

        accion = estado.modificar
    End Sub

    'BOTON ELIMINAR
    Private Sub btn_eliminar_Click(sender As System.Object, e As System.EventArgs) Handles btn_eliminar.Click
        If MsgBox("¿Realmente desea Borrar?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Importante") = MsgBoxResult.No Then
            Me.primera_busqueda = False
            Exit Sub
        End If

        Me.eliminar()

        Me.carga_grilla()

        limpiar_campos()

        Me.btn_eliminar.Enabled = False
        Me.btn_buscar.Enabled = False
        Me.btn_guardar.Enabled = False
        Me.primera_busqueda = False

        Me.deshabilitar_Campos()
    End Sub

    'FUNCION PARA ELIMINAR
    Private Function eliminar() As termino
        Dim comando As String = ""

        comando = "DELETE FROM Detalle_Egreso "
        comando += "WHERE cod_Egreso=" & codigo_Egreso

        Try
            acceso._borrar(comando)
            Return termino.aprobado
        Catch ex As Exception
            MessageBox.Show("Error al Eliminar DETALLE EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return termino.rechazado
            Exit Function
        End Try

        comando = "DELETE FROM Egreso "
        comando += "WHERE cod_Egreso=" & codigo_Egreso

        Try
            acceso._borrar(comando)
            Return termino.aprobado
        Catch ex2 As Exception
            MessageBox.Show("Error al Eliminar EGRESO en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex2.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)


            Return termino.rechazado
            Exit Function
        End Try
    End Function
    Private Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        Busqueda_Egreso.Show()
    End Sub

    Private Sub txt_docu_come_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_docu_come.KeyPress, txt_Monto.KeyPress
        Select Case Asc(e.KeyChar)
            Case 4, 24, 4, 19, 127, 13, 9, 15, 14, 8, 46
                Exit Sub
        End Select

        If IsNumeric(e.KeyChar) = False Then
            e.KeyChar = ""
        End If
    End Sub

    Private Sub Planilla_Egreso_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        Dispose()
    End Sub

    Private Sub txt_desc_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_desc.Leave
        If txt_desc.Text = "" And btn_volver.Focused = False Then
            lbl_descripcion_obligatorio.Visible = True
        Else
            lbl_descripcion_obligatorio.Visible = False
        End If
    End Sub

    Private Sub txt_prov_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_prov.Leave
        If txt_prov.Text = "" And btn_volver.Focused = False Then
            lbl_proveedor_obligatorio.Visible = True
        Else
            lbl_proveedor_obligatorio.Visible = False
        End If
    End Sub

    Private Sub txt_docu_come_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_docu_come.Leave
        If txt_docu_come.Text = "" And btn_volver.Focused = False Then
            lbl_documento_obligatorio.Visible = True
        Else
            lbl_documento_obligatorio.Visible = False
        End If
    End Sub

    Private Sub txt_Monto_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_Monto.Leave
        If txt_Monto.Text = "" And btn_volver.Focused = False Then
            lbl_monto_obligatorio.Visible = True
        Else
            lbl_monto_obligatorio.Visible = False
        End If
    End Sub

    Public Sub indicar_obligatorios(ByVal sender As System.Object, ByVal e As System.EventArgs)
        txt_desc_Leave(sender, e)
        txt_prov_Leave(sender, e)
        txt_docu_come_Leave(sender, e)
        txt_Monto_Leave(sender, e)
    End Sub
End Class